package com.degon.hsyl.mychat;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private EditText phoneNumber;
    private Button getVerifyCode;
    private EditText verifyCode;
    private Button login;

    private Handler handler;

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();

        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 1) {
                    LoginResponseModel data = (LoginResponseModel) msg.obj;
                    getRongYunToken(data);
                }
            }
        };

        getVerifyCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (phoneNumber.getText().toString().equals("") || phoneNumber.getText().toString().length() != 11) {
                    ToastUtils.showShort("手机号码格式不正确,请重新输入");
                } else {
                    getCodeFun();
                }
            }
        });

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (verifyCode.getText().toString().length() != 5) {
                    ToastUtils.showShort("验证码格式不正确");
                } else {
                    saveUserData();
                    startActivity(new Intent(MainActivity.this, MainActivity2.class));
                    finish();
                }
            }
        });

    }

    private void getRongYunToken(LoginResponseModel data) {
        String url = "https://api-cn.ronghub.com/user/getToken.json";
        RequestBody body = new FormBody.Builder()
                .add("userId", data.getData().getUser().getRongcloud_user_id())
                .add("name", data.getData().getUser().getUsername())
                .add("portraitUri", data.getData().getUser().getHead_portrait())
                .build();
        new Thread() {
            @Override
            public void run() {
                try {
                    Response response = HttpUtil.rongYunPost(url, body);
                    GetRongYunTokenResponseModel model = new Gson().fromJson(response.body().string(), GetRongYunTokenResponseModel.class);
                    SharedPreferences.Editor editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit();
                    editor.putString("rongYunToken", model.getToken());
                    editor.apply();
                } catch (IOException | NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void saveUserData() {
        String url = HttpUtil.yuMing + "/api/api_user/sms_login";
        RequestBody body = new FormBody.Builder()
                .add("mobile", phoneNumber.getText().toString())
                .add("access_token", phoneNumber.getText().toString())
                .add("verify_code", verifyCode.getText().toString())
                .build();
        new Thread() {
            @Override
            public void run() {
                try {
                    Response response = HttpUtil.post(url, body);
                    LoginResponseModel model = new Gson().fromJson(response.body().string(), LoginResponseModel.class);
                    if (model.getStatus() == 1) {
                        SharedPreferences.Editor editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit();
                        editor.putString("userToken", model.getData().getAccess_token());
                        editor.putString("userName", model.getData().getUser().getUsername());
                        editor.putString("headPortrait", model.getData().getUser().getHead_portrait());
                        editor.putString("rongYunId", model.getData().getUser().getRongcloud_user_id());
                        editor.apply();

                        Message message = new Message();
                        message.what = 1;
                        message.obj = model;
                        handler.handleMessage(message);
                    } else {
                        ToastUtils.showShort(model.getMsg());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void initViews() {
        phoneNumber = findViewById(R.id.phone_number);
        getVerifyCode = findViewById(R.id.get_code);
        verifyCode = findViewById(R.id.verify_code);
        login = findViewById(R.id.log_in);
    }

    private void getCodeFun() {
        String url = HttpUtil.yuMing + "/api/verify-code";
        RequestBody body = new FormBody.Builder()
                .add("mobile", phoneNumber.getText().toString())
                .add("access_token", phoneNumber.getText().toString())
                .add("mobile_rule", "mobile_required")
                .build();
        new Thread() {
            @Override
            public void run() {
                try {
                    Response response = HttpUtil.post(url, body);
                    GetCodeResponseModel model = new Gson().fromJson(response.body().string(), GetCodeResponseModel.class);
                    ToastUtils.showShort(model.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}